package com.robot.console;

import com.robot.console.client.Client;
import com.robot.console.config.CsConfig;
import com.robot.console.config.HaConfigBuilder;
import com.robot.console.core.ClientCommonParam;
import com.robot.console.core.ClientInfo;

import java.util.Scanner;

import static com.google.common.base.Preconditions.checkNotNull;

public class ClientConsole
{

	public static final String ETC_WEB_FILE = "web-config.xml";
	public static final String ETC_MOBIL_FILE = "mobil-config.xml";

	public static void main(String[] args)
	{
		try
		{
			int index = 0;
			if (args.length > 0 && args[0].equals("mobil"))
			{
				HaConfigBuilder.loadConfig(ETC_MOBIL_FILE);
			}
			else
			{
				HaConfigBuilder.loadConfig(ETC_WEB_FILE);
			}

			if (args.length == 1 && args[0].equals("0"))
			{
				index = 0;
			}
			else if (args.length == 1 && args[0].equals("1"))
			{
				index = 1;
			}
			else if (args.length == 1 && args[0].equals("2"))
			{
				index = 2;
			}

			CsConfig config = (CsConfig) HaConfigBuilder.getCsconfigs().get(0);
			ClientInfo clientInfo = HaConfigBuilder.getRobotinfolist().get(index);
			Client client = new Client(config, clientInfo);
			client.init();
			consoleLoop(client);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	private static void consoleLoop(Client client)
	{
		checkNotNull(client);

		try
		{
			@SuppressWarnings("resource")
			Scanner input = new Scanner(System.in);
			printWelcome();
			String inputInfo = input.nextLine();
			do
			{
				String[] info = inputInfo.split(" ");
				if ("connect".equalsIgnoreCase(info[0]))
				{
					String[] addressArray = inputInfo.split(" ");
					if (addressArray.length == 2)
					{
						client.connect(addressArray[1]);
					}
					else
					{
						client.connect();
					}
				}
				else if ("disconnect".equalsIgnoreCase(info[0]))
				{
					client.disconnect();
				}
				else
				{
					client.takeAction(inputInfo);
				}
				ClientCommonParam.printInputLine();

			} while (!("quit".equalsIgnoreCase(inputInfo = input.nextLine())));

			client.shutdown();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private static void printWelcome()
	{
		System.out.println("||=====|| : Hello Client!");
		ClientCommonParam.printInputLine();

	}
}
